package com.common.aliyun.sms.template;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.common.aliyun.sms.properties.SmsProperties;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhengzg
 * @create 2023-09-18 9:16
 */
@Slf4j
public class SmsTemplate {

    private final SmsProperties smsProperties;

    public SmsTemplate(SmsProperties smsProperties) {
        this.smsProperties = smsProperties;
    }

    /**
     * 发送短信验证码服务
     *
     * @param mobile 手机号
     * @param code   验证码
     * @return 是否成功
     */
    public boolean sendCode(String mobile, String code) {
        try {
            Config config = new Config()
                    .setAccessKeyId(smsProperties.getAccessKey())
                    .setAccessKeySecret(smsProperties.getSecret());

            // 访问的域名
            config.endpoint = smsProperties.getEndpoint();

            Client client = new Client(config);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(mobile)
                    .setSignName(smsProperties.getSignName())
                    .setTemplateCode(smsProperties.getTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");

            SendSmsResponse response = client.sendSms(sendSmsRequest);

            SendSmsResponseBody body = response.getBody();

            // 打印返回信息
            log.info("<---------- 阿里云信息服务调用返回结果：{} ----------->", body.getMessage());
            return true;
        } catch (Exception e) {
            log.error("<------------- 阿里云短信服务调用失败：失败原因：{} ------------->", e.getMessage());
        }

        return false;
    }

}
